package com.ztn.iot.zhonghaichi.push;

import com.ztn.base.util.common.HttpClientTool;
import com.ztn.base.util.common.JsonTool;
import com.ztn.base.util.common.TimeTool;
import com.ztn.iot.zhonghaichi.entity.PushHistoryEntity;
import com.ztn.iot.zhonghaichi.fun.SensorFun;
import com.ztn.iot.zhonghaichi.mapper.PushHistoryMapper;
import com.ztn.iot.zhonghaichi.properties.ZhcProperties;
import com.ztn.iot.zhonghaichi.push.req.PushFlowReq;
import com.ztn.iot.zhonghaichi.push.req.PushRainReq;
import com.ztn.iot.zhonghaichi.push.req.PushWaterReq;
import com.ztn.iot.zhonghaichi.push.res.PushRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;

import static com.ztn.base.util.common.HttpClientTool.DEFAULT_CHARSET;

@Slf4j
@Component
public class DataPushApi {

    @Autowired
    private ZhcProperties zhcProperties;

    @Autowired
    private SensorFun sensorFun;

    @Autowired
    private PushHistoryMapper pushHistoryMapper;


    public void pushRain(int time, String siteCode, Double rainCount, Double hourRainCount, Double dayRainCount) {
        if (!StringUtils.hasText(siteCode)) {
            return;
        }
        final String date = TimeTool.timeStamp2Date(time);
        PushRainReq req = new PushRainReq();
        req.setSTCD(siteCode);
        req.setTM(date);
        req.setDRP(null != rainCount && rainCount > 0 ? rainCount : 0D);
        req.setHRP(null != hourRainCount && hourRainCount > 0 ? hourRainCount : 0D);
        req.setDYP(null != dayRainCount && dayRainCount > 0 ? dayRainCount : 0D);
        zhcProperties.getZhcAuths().forEach(zhmAuth -> {
            Map<String, Object> headers = TokenGetApi.getHeaders(zhmAuth.getBaseUrl());
            if (null == headers) {
                return;
            }
            String url = zhmAuth.getBaseUrl() + PushRainReq.URL;
            String requestBody = JsonTool.toJson(req);
            try {
                final CloseableHttpResponse closeableHttpResponse = HttpClientTool.postJsonStrWithHeaderForRes(url, requestBody, headers, null);
                resHandler(zhmAuth, requestBody, url, headers, closeableHttpResponse);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    public void pushFlow(int time, String siteCode, Double speed, Double flow, Double dept, Double flowCount) {
        if (!StringUtils.hasText(siteCode)) {
            return;
        }
        final String date = TimeTool.timeStamp2Date(time);
        PushFlowReq req = new PushFlowReq();
        req.setSTCD(siteCode);
        req.setTM(date);
        req.setLIULIANG(null != flow && flow > 0 ? flow : 0);
        req.setLIUSU(null != speed && speed > 0 ? speed : 0);
        req.setSHUIWEI(null != dept && dept > 0 ? dept : 0);
        req.setTOTALLIULIANG(null != flowCount && flowCount > 0 ? flowCount : 0);
        zhcProperties.getZhcAuths().forEach(zhmAuth -> {
            Map<String, Object> headers = TokenGetApi.getHeaders(zhmAuth.getBaseUrl());
            if (null == headers) {
                return;
            }
            String url = zhmAuth.getBaseUrl() + PushFlowReq.URL;
            String requestBody = JsonTool.toJson(req);
            try {
                final CloseableHttpResponse closeableHttpResponse = HttpClientTool.postJsonStrWithHeaderForRes(url, requestBody, headers, null);
                resHandler(zhmAuth, requestBody, url, headers, closeableHttpResponse);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }


    public void pushWater(int time, String siteCode, Double waterDept, Double siteStorage, Double input, Double output, Double warnWaterDept) {
        if (!StringUtils.hasText(siteCode)) {
            return;
        }

        final String date = TimeTool.timeStamp2Date(time);
        PushWaterReq req = new PushWaterReq();
        req.setSTCD(siteCode);
        req.setTM(date);
        req.setRZ(null != waterDept && waterDept > 0 ? waterDept : 0);
        req.setW(null != siteStorage && siteStorage > 0 ? siteStorage : 0);
        req.setINQ(null != input && input > 0 ? input : 0);
        req.setOTQ(null != output && output > 0 ? output : 0);
        req.setFSLTDZ(null != warnWaterDept && warnWaterDept > 0 ? warnWaterDept : 0);
        zhcProperties.getZhcAuths().forEach(zhmAuth -> {
            Map<String, Object> headers = TokenGetApi.getHeaders(zhmAuth.getBaseUrl());
            if (null == headers) {
                return;
            }
            String url = zhmAuth.getBaseUrl() + PushWaterReq.URL;
            String requestBody = JsonTool.toJson(req);
            try {
                final CloseableHttpResponse closeableHttpResponse = HttpClientTool.postJsonStrWithHeaderForRes(url, requestBody, headers, null);
                resHandler(zhmAuth, requestBody, url, headers, closeableHttpResponse);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }


    void resHandler(ZhcProperties.ZhcAuth zhcAuth, String requestBody, String url, Map<String, Object> headers, CloseableHttpResponse closeableHttpResponse) {
        saveHistory(closeableHttpResponse.getStatusLine().getStatusCode(), url, requestBody);
        if (closeableHttpResponse.getStatusLine().getStatusCode() == 401) {
            sensorFun.updateToken();
            return;
        }
        if (closeableHttpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.error("url:{},requestBody:{},header:{},statusCode:{}", url, requestBody, JsonTool.toJson(headers), closeableHttpResponse.getStatusLine().getStatusCode());
            return;
        }
        String str = null;
        try {
            str = EntityUtils.toString(closeableHttpResponse.getEntity(), DEFAULT_CHARSET);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != closeableHttpResponse) {
                try {
                    closeableHttpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        final PushRes pushRes = JsonTool.fromJson(str, PushRes.class);
        if (null == pushRes) {
            log.error("{} null==pushRes", zhcAuth.getBaseUrl());
        } else if (pushRes.getCode() != 200) {
            log.error("{} pushRes.getCode() != 200", zhcAuth.getBaseUrl());
            log.error(requestBody);
            System.out.println(pushRes);
        } else {
//            log.info("success push {} {}", url, requestBody);
        }
    }


    public void saveHistory(int code, String url, String msg) {
        PushHistoryEntity pushHistoryEntity = new PushHistoryEntity();
        pushHistoryEntity.setCode(code);
        pushHistoryEntity.setUrl(url);
        pushHistoryEntity.setMsg(msg);
        pushHistoryMapper.insert(pushHistoryEntity);
    }

}
